package kr.saeildamil.androidstudy.ch17;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class SaveState extends Activity {
	private MyView vw;
	int x;
	int y;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(savedInstanceState==null){
			x = 50;
		}else{
			x = savedInstanceState.getInt("x");
		}
		
		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		y = pref.getInt("y", 50);
		
		vw = new MyView(this);
		vw.setFocusable(true);
		vw.setFocusableInTouchMode(true);
		setContentView(vw);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putInt("y", y);
		edit.commit();
	}
	
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if(savedInstanceState==null){
			x = 50;
		}else{
			x = savedInstanceState.getInt("x");
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("x", x);   //x값만 지정
	}
	
	protected class MyView extends View{

		public MyView(Context context) {
			super(context);
	}	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint p = new Paint();	
		p.setColor(Color.GREEN);
		canvas.drawCircle(x, y, 16, p);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		if(event.getAction()== MotionEvent.ACTION_DOWN){
			x += 15;
			y += 15;
			invalidate();
			return true;
		}
		return false;
	}
  }
}
